package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.LoginHistroyMapper;
import com.lst.entity.request.ClientReqPara;
import com.lst.entity.response.ClientResPara;
import com.lst.model.LoginHistroy;
import com.lst.model.MstClient;
import com.lst.service.MstClientService;
import com.lst.service.OpenImUserService;
import com.lst.utils.RequestUtils;
import com.lst.utils.TokenProcessor;

/**
 * @ClassName: LoginServlet
 * @Description: 登录接口
 * @author zmm
 * @date 2017年9月22日 上午10:35:28
 * 
 */
public class LoginServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private MstClientService mstClientService = ctx.getBean(MstClientService.class);

	private OpenImUserService openImUserService = ctx.getBean(OpenImUserService.class);

	private LoginHistroyMapper loginHistroyMapper = ctx.getBean(LoginHistroyMapper.class);


	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		ClientResPara resPara = new ClientResPara();

		try {
			ClientReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {
				String account = reqPara.getAccount();
				String password = reqPara.getPassword();
				String logintype = reqPara.getLogintype();
				String nickname = reqPara.getNickname();
				String gender = reqPara.getGender();
				String portrait = reqPara.getPortrait();
				String thirdno = reqPara.getThirdno();

				if(CommCode.SYSTEM_LOGINTYPE_MOBILENO.toString().equals(logintype)
						|| CommCode.SYSTEM_LOGINTYPE_MAIL.toString().equals(logintype)){				

					boolean checkaccount = checkaccount(account);	

					if(checkaccount){
						// 登录
						MstClient mstClient = loginByKungFu(account, password, logintype);

						// 业务逻辑处理
						if (mstClient == null) {
							resPara.setCode(CommCode.M_A000000);
							resPara.setMessage(CommCode.M_C000007);
						} else {
							// 初始化openim用户
							mstClient = openImUserService.OpenImUserInit(mstClient);

							// 隐藏手机号中间字符
							if (!StringUtils.isEmpty(mstClient.getMobileno())) {
								String mobile = mstClient.getMobileno().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
								mstClient.setMobile(mobile);
							}

							resPara.setMstClient(mstClient);

							//生成token,保存到登陆记录表里
							 String token = new TokenProcessor().generateToken("martkungfu",true); 
							// 记录登陆
							LoginHistroy lh = new LoginHistroy();
							lh.setClientid(mstClient.getId());
							lh.setLogindate(new Date());
							lh.setEnabled(true);
							lh.setIsdeleted(false);
							lh.setCreatedate(new Date());
							lh.setCreateuser(mstClient.getId());
							lh.setReserved9(token);

							loginHistroyMapper.insert(lh);

							resPara.setCode(CommCode.M_Y000000);
							resPara.setMessage(CommCode.M_Y000001);
							resPara.setToken(token);
						}
					}else{
						resPara.setCode(CommCode.M_A000000);
						resPara.setMessage(CommCode.M_C000028);
					}
				}else{
					MstClient mstClient = loginByThird(logintype, nickname, gender, portrait, thirdno);

					// 业务逻辑处理
					if (mstClient == null) {
						resPara.setCode(CommCode.M_A000000);
						resPara.setMessage(CommCode.M_C000007);
					} else {
						// 初始化openim用户
						mstClient = openImUserService.OpenImUserInit(mstClient);

						// 隐藏手机号中间字符
						if (!StringUtils.isEmpty(mstClient.getMobileno())) {
							String mobile = mstClient.getMobileno().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
							mstClient.setMobile(mobile);
						}

						resPara.setMstClient(mstClient);

						//生成token,保存到登陆记录表里
						 String token = new TokenProcessor().generateToken("martkungfu",true); 
						// 记录登陆
						LoginHistroy lh = new LoginHistroy();
						lh.setClientid(mstClient.getId());
						lh.setLogindate(new Date());
						lh.setEnabled(true);
						lh.setIsdeleted(false);
						lh.setCreatedate(new Date());
						lh.setCreateuser(mstClient.getId());
						lh.setReserved9(token);

						loginHistroyMapper.insert(lh);

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_Y000001);
						resPara.setToken(token);
					}
				}
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.excludeFieldsWithoutExposeAnnotation().serializeNulls()
					.create();
			String jsonResult = gson.toJson(resPara);
//			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

//			logger.info("doPost end run(s): "
//					+ DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientReqPara getReqPara(HttpServletRequest request) {

		ClientReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,
					new ClientReqPara());

			reqPara = (ClientReqPara) baseRequest.clone();

			String logintype = request.getParameter("logintype");
			String account = request.getParameter("account");
			String password = request.getParameter("password");
			String nickname = request.getParameter("nickname");
			String portrait = request.getParameter("portrait");
			String gender = request.getParameter("gender");
			String thirdno = request.getParameter("thirdno");

//			logger.info("reqPara logintype: " + logintype);
//			logger.info("reqPara account: " + account);
//			logger.info("reqPara password: " + password);
//			logger.info("reqPara nickname: " + nickname);
//			logger.info("reqPara portrait: " + portrait);
//			logger.info("reqPara gender: " + gender);
//			logger.info("reqPara thirdno: " + thirdno);

			reqPara.setLogintype(logintype);
			reqPara.setAccount(account);
			reqPara.setPassword(password);
			reqPara.setNickname(nickname);
			reqPara.setPortrait(portrait);
			reqPara.setGender(gender);
			reqPara.setThirdno(thirdno);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientReqPara loginReqPara = (ClientReqPara) reqPara;
		ClientResPara loginResPara = (ClientResPara) resPara;

		if (StringUtils.isEmpty(loginReqPara.getLogintype())) {
			loginResPara.setCode(CommCode.M_A000000);
			loginResPara.setMessage(CommCode.M_C000024);
		} else {

			if (CommCode.SYSTEM_LOGINTYPE_MOBILENO.toString().equals(
					loginReqPara.getLogintype())
					|| CommCode.SYSTEM_LOGINTYPE_MAIL.toString().equals(
							loginReqPara.getLogintype())) {
				if (StringUtils.isEmpty(loginReqPara.getAccount())) {
					loginResPara.setCode(CommCode.M_A000000);
					loginResPara.setMessage(CommCode.M_C000001);
				} else if (StringUtils.isEmpty(loginReqPara.getPassword())) {
					loginResPara.setCode(CommCode.M_A000000);
					loginResPara.setMessage(CommCode.M_C000002);
				} else {
					flag = true;
				}
			} else {
				if (StringUtils.isEmpty(loginReqPara.getThirdno())) {
					loginResPara.setCode(CommCode.M_A000000);
					loginResPara.setMessage(CommCode.M_C000025);
				} else {
					flag = true;
				}
			}

		}

		return flag;
	}

	/**************************** 辅助方法 *******************************************/

	private boolean checkaccount(String account) {

		boolean check= false;

		Map<String, Object> checkmap = new HashMap<String, Object>();

		checkmap.put("mobileno", account);
		checkmap.put("enabled", true);
		checkmap.put("isDeleted", false);

		List<MstClient> list = mstClientService.queryByList(checkmap,new PageBounds());

		if(list.isEmpty()){
			check = false;
		}else{
			check = true;
		}

		return check;
	}

	/**
	 * @Title: loginByThird
	 * @Description: 第三方平台登录
	 * @param @param logintype
	 * @param @param nickname
	 * @param @param gender
	 * @param @param portrait
	 * @param @param thirdno 设定文件
	 * @return MstClient 返回类型
	 */
	private MstClient loginByThird(String logintype, String nickname,
			String gender, String portrait, String thirdno) {
		MstClient mstClient = null;

		Map<String, Object> reqMap = new HashMap<String, Object>();
	//	reqMap.put("loginType", logintype);
		if(CommCode.SYSTEM_LOGINTYPE_WEIXIN.toString().equals(logintype)){
			reqMap.put("thirdNo", thirdno);
		}
		if(CommCode.SYSTEM_LOGINTYPE_QQ.toString().equals(logintype)){
			reqMap.put("thirdNoqq", thirdno);
		}		
		if(CommCode.SYSTEM_LOGINTYPE_SINA.toString().equals(logintype)){
			reqMap.put("thirdNowb", thirdno);
		}
		reqMap.put("enabled", true);
		reqMap.put("isDeleted", false);

		List<MstClient> mstClisnts = mstClientService.queryByList(reqMap,
				new PageBounds());

		if (mstClisnts.isEmpty()) {
			// 注册新账号
			mstClient = new MstClient();
			mstClient.setCreatedate(new Date());
			mstClient.setEnabled(true);
			if ("0".equals(gender)) {
				mstClient.setGender(false);
			} else {
				mstClient.setGender(true);
			}
			mstClient.setIsdeleted(false);

			mstClient.setLogintype(Integer.valueOf(logintype));
			if(CommCode.SYSTEM_LOGINTYPE_WEIXIN.toString().equals(logintype)){
				mstClient.setThirdno(thirdno);
			}
			if(CommCode.SYSTEM_LOGINTYPE_QQ.toString().equals(logintype)){
				mstClient.setThirdnoqq(thirdno);
			}		
			if(CommCode.SYSTEM_LOGINTYPE_SINA.toString().equals(logintype)){
				mstClient.setThirdnowb(thirdno);
			}
			mstClient.setPortrait(portrait);
			mstClient.setNickname(StringUtils.isEmpty(nickname) ? "功夫小白": nickname);

			mstClientService.insert(mstClient);

			return mstClient;
		} else {
			mstClient = mstClisnts.isEmpty() ? null : mstClisnts.get(0);
//			mstClient.setNickname(nickname);
//			mstClient.setPortrait(portrait);
//			mstClient.setReserved11(portrait);
//			mstClientService.updateByPrimaryKeySelective(mstClient);
		}

		return mstClient;
	}

	/**
	 * 
	 * @Title: loginByKungFu
	 * @Description: 功夫平台登录
	 * @param @param account
	 * @param @param password
	 * @param @param logintype
	 * @param @return 设定文件
	 * @return MstClient 返回类型
	 */
	private MstClient loginByKungFu(String account, String password,
			String logintype) {
		Map<String, Object> reqMap = new HashMap<String, Object>();

		reqMap.put("password", password);
		reqMap.put("enabled", true);
		reqMap.put("isDeleted", false);
	//	reqMap.put("loginType", logintype);

		// 正则校验
		Pattern mailPat = Pattern.compile(CommCode.REGEX_EMAIL);
		// Pattern mobilenoPat = Pattern.compile(CommCode.REGEX_MOBILE);
		Matcher mailMat = mailPat.matcher(account);
		// Matcher mobilenoMat = mobilenoPat.matcher(account);

		if (mailMat.matches()) {
			reqMap.put("email", account);
		} else {
			reqMap.put("mobileno", account);
		}

		List<MstClient> list = mstClientService.queryByList(reqMap,new PageBounds());

		MstClient mstClient = list.isEmpty() ? null : list.get(0);

		return mstClient;
	}
}
